import React, {
  useState,
  useEffect,
  useCallback,
  useMemo,
  useRef,
} from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { ProjectAPI } from "@/api/project";
import { TensionSectionAPI } from "@/api/tensionSection";
import { CrossingPointAPI } from "@/api/CrossingPoint";
import { ConstructionSchemeAPI } from "@/api/ConstructionScheme";
import { ConstructionMethodTemplateAPI } from "@/api/ConstructionMethodTemplate";

import { createPageUrl } from "@/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  FileText,
  Plus,
  Filter,
  Search,
  MoreVertical,
  Clock,
  CheckCircle,
  XCircle,
  Loader,
  AlertCircle,
  Info,
  ChevronRight,
  Eye,
  Edit,
  Trash2,
  Copy,
  FileDown,
  Loader2,
  RefreshCw,
  AlertTriangle,
  Wifi,
  WifiOff,
  X,
  ChevronDown,
  Wand2,
} from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";

import SchemeForm from "../components/schemes/SchemeForm";
import SchemeCard from "../components/schemes/SchemeCard";
import SchemeFilters from "../components/schemes/SchemeFilters";

// 优化的API调用策略：延迟函数
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

/**
 * API调用重试逻辑
 * @param {Function} apiCall - 返回Promise的API调用函数（确保参数为对象）
 * @param {number} maxRetries - 最大重试次数
 * @param {number} initialDelay - 初始重试延迟（ms）
 * @returns {Promise} - API返回结果
 */
const apiCallWithRetry = async (
  apiCall,
  maxRetries = 2,
  initialDelay = 1000
) => {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const result = await apiCall();
      return result;
    } catch (error) {
      console.error(`API调用失败 (尝试 ${attempt}/${maxRetries}):`, error);
      // 识别限流错误
      const isRateLimitError =
        error.message?.includes("429") ||
        error.message?.includes("Rate limit") ||
        error.response?.status === 429;

      // 未到最大重试次数，延迟后重试
      if (attempt < maxRetries) {
        const delayTime = isRateLimitError
          ? Math.max(3000, initialDelay * Math.pow(2, attempt)) // 限流错误指数退避
          : initialDelay * attempt;

        console.log(`等待 ${delayTime}ms 后重试...`);
        await delay(delayTime);
        continue;
      }

      // 最后一次尝试失败，抛出错误
      throw error;
    }
  }
};

// 安全数组转换函数：确保返回数组
const ensureArray = (data) => (Array.isArray(data) ? data : []);

// 映射审批状态到UI显示：统一状态样式
const statusMap = {
  draft: {
    label: "草稿",
    color: "bg-gray-100 text-gray-800",
    icon: <Info className="w-3 h-3" />,
  },
  submitted: {
    label: "审批中",
    color: "bg-blue-100 text-blue-800",
    icon: <Loader className="w-3 h-3 animate-spin" />,
  },
  approved: {
    label: "已批准",
    color: "bg-green-100 text-green-800",
    icon: <CheckCircle className="w-3 h-3" />,
  },
  rejected: {
    label: "已驳回",
    color: "bg-red-100 text-red-800",
    icon: <XCircle className="w-3 h-3" />,
  },
  notStarted: {
    label: "未开始",
    color: "bg-yellow-100 text-yellow-800",
    icon: <Clock className="w-3 h-3" />,
  },
  inProgress: {
    label: "进行中",
    color: "bg-blue-100 text-blue-800",
    icon: <Loader className="w-3 h-3 animate-spin" />,
  },
  completed: {
    label: "已完成",
    color: "bg-green-100 text-green-800",
    icon: <CheckCircle className="w-3 h-3" />,
  },
};

export default function ConstructionSchemes() {
  // 核心数据状态
  const [schemes, setSchemes] = useState([]);
  const [projects, setProjects] = useState([]);
  const [tensionSections, setTensionSections] = useState([]);
  const [crossingPoints, setCrossingPoints] = useState([]);
  const [methodTemplates, setMethodTemplates] = useState([]);
  const [standards, setStandards] = useState([]);

  // 加载与交互状态
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [filters, setFilters] = useState({
    projectId: "all",
    approvalStatus: "all",
    constructionMethod: "all",
  });
  const [isFormVisible, setIsFormVisible] = useState(false);
  const [editingScheme, setEditingScheme] = useState(null);
  const [filteredSchemes, setFilteredSchemes] = useState([]);

  // 错误与警告状态
  const [error, setError] = useState(null);
  const [lastSuccessfulLoad, setLastSuccessfulLoad] = useState(null);

  // 项目展开状态（分组显示用）
  const [expandedProjects, setExpandedProjects] = useState({});
  const isLoadingRef = useRef(false); // 防止重复加载的引用

  // 路由与提示工具
  const navigate = useNavigate();
  const location = useLocation();
  const { toast } = useToast();

  /**
   * 加载所有数据（核心函数）
   * @param {boolean} forceRefresh - 是否强制刷新（忽略缓存）
   * @param {boolean} showToastMessage - 是否显示加载结果提示
   */
  const loadAllData = useCallback(
    async (forceRefresh = false, showToastMessage = false) => {
      // 防止重复加载
      if (isLoadingRef.current && !forceRefresh) {
        console.log("⏭️ 跳过数据加载，另一个加载正在进行中");
        return;
      }
      isLoadingRef.current = true;
      setIsLoading(true);
      setError(null);
      console.log(
        "🔄 开始加载施工方案数据...",
        forceRefresh ? "(强制刷新)" : ""
      );

      try {
        // 1. 加载项目数据（传空对象确保参数为对象类型）
        console.log("📊 1/5 加载项目数据...");
        const projectsData = await apiCallWithRetry(
          () => ProjectAPI.getList({}) // 修复：传递空对象，避免undefined
        );
        const projectsArray = ensureArray(projectsData.data);
        setProjects(projectsArray);
        console.log("✅ 项目数据加载完成:", projectsArray.length, "条");
        await delay(80);

        // 2. 加载勘查单数据（传空对象）
        console.log("📊 2/5 加载勘查单数据...");
        const tensionSectionsData = await apiCallWithRetry(
          () => TensionSectionAPI.getList({}) // 修复：传递空对象
        );
        const tensionSectionsArray = ensureArray(tensionSectionsData.data);
        setTensionSections(tensionSectionsArray);
        console.log(
          "✅ 勘查单数据加载完成:",
          tensionSectionsArray.length,
          "条"
        );
        await delay(80);

        // 3. 加载跨越点数据（传空对象）
        console.log("📊 3/5 加载跨越点数据...");
        const crossingPointsData = await apiCallWithRetry(
          () => CrossingPointAPI.getList({}) // 修复：传递空对象
        );

        const crossingPointsArray = ensureArray(crossingPointsData.data);
        setCrossingPoints(crossingPointsArray);
        console.log("✅ 跨越点数据加载完成:", crossingPointsArray.length, "条");
        await delay(80);

        // 4. 加载施工方案数据（排序参数包装为对象）
        const schemesData = await apiCallWithRetry(
          () => ConstructionSchemeAPI.getList({ sort: "-created_date" }) // 修复：字符串参数→对象参数
        );
        const schemesArray = ensureArray(schemesData.data);

        // 5. 加载方法模板数据（传空对象）
        const methodTemplatesData = await apiCallWithRetry(
          () => ConstructionMethodTemplateAPI.getList({}) // 修复：传递空对象
        );
        const templatesArray = ensureArray(methodTemplatesData.data); // 假设返回data字段
        setMethodTemplates(templatesArray);
        console.log("✅ 方法模板数据加载完成:", templatesArray.length, "条");

        // 丰富方案数据（关联项目、勘查单名称）
        const enrichedSchemes = schemesArray.map((scheme) => {
          const tensionSection = tensionSectionsArray.find(
            (ts) => ts.id === scheme.tensionSectionId
          );
          const project = tensionSection
            ? projectsArray.find((p) => p.id === tensionSection.projectId)
            : null;

          return {
            ...scheme,
            tensionSectionName: tensionSection
              ? tensionSection.name
              : "孤立勘查单",
            projectName: project ? project.name : "未知项目",
            projectId: project ? project.id : null,
            approvalStatus: scheme.approvalStatus || "draft", // 默认草稿状态
          };
        });

        // 更新状态
        setSchemes(enrichedSchemes);
        setLastSuccessfulLoad(new Date());

        // 显示加载成功提示
        if (showToastMessage) {
          toast({
            title: "数据加载成功",
            description: `共加载 ${enrichedSchemes.length} 个施工方案`,
          });
        }

        console.log("✅ 所有数据加载完成");
      } catch (error) {
        console.error("❌ 方案数据加载失败:", error);

        // 错误信息分类
        let errorMessage = "加载数据时发生错误";
        if (
          error.message?.includes("429") ||
          (error.response && error.response.status === 429)
        ) {
          errorMessage = "请求过于频繁，请5分钟后重试";
        } else if (
          error.message?.includes("Network Error") ||
          error.message?.includes("Failed to fetch")
        ) {
        } else {
          errorMessage = error.message || "未知错误";
        }

        setError(errorMessage);

        // 仅在无数据时清空状态
        if (!schemes.length) {
          setSchemes([]);
          setProjects([]);
          setTensionSections([]);
          setCrossingPoints([]);
          setMethodTemplates([]);
        }

        // 显示加载失败提示
        if (showToastMessage) {
          toast({
            variant: "destructive",
            title: "数据加载失败",
            description: errorMessage,
          });
        }
      } finally {
        setIsLoading(false);
        isLoadingRef.current = false;
      }
    },
    [toast, schemes.length]
  );

  /**
   * 初始加载数据
   */
  useEffect(() => {
    loadAllData();
  }, [loadAllData]);

  useEffect(() => {
    let currentFiltered = ensureArray(schemes).filter(
      (scheme) => scheme.projectId !== null && scheme.projectName !== "未知项目"
    );

    // 搜索过滤
    if (searchTerm) {
      const lowerTerm = searchTerm.toLowerCase();
      currentFiltered = currentFiltered.filter(
        (scheme) =>
          scheme.name?.toLowerCase().includes(lowerTerm) ||
          scheme.constructionMethod?.toLowerCase().includes(lowerTerm) ||
          scheme.tensionSectionName?.toLowerCase().includes(lowerTerm)
      );
    }

    // 项目筛选（现在filters更新后会生效）
    if (filters.projectId !== "all") {
      currentFiltered = currentFiltered.filter(
        (scheme) => scheme.projectId === filters.projectId
      );
    }

    // 其他筛选（状态、施工方法）
    if (filters.approvalStatus !== "all") {
      currentFiltered = currentFiltered.filter(
        (scheme) => scheme.approvalStatus === filters.approvalStatus
      );
    }
    if (filters.constructionMethod !== "all") {
      currentFiltered = currentFiltered.filter(
        (scheme) => scheme.constructionMethod === filters.constructionMethod
      );
    }

    setFilteredSchemes(currentFiltered);
  }, [schemes, searchTerm, filters]); // 依赖filters，状态更新即触发筛选

  /**
   * 切换项目展开/折叠状态
   */
  const toggleProjectExpansion = useCallback((projectId) => {
    setExpandedProjects((prev) => ({
      ...prev,
      [projectId]: !prev[projectId],
    }));
  }, []);

  /**
   * 处理筛选条件变化
   */
  // const handleFilterChange = (key, value) => {
  //   console.log(key, "key, valuekey, value");
  //   console.log(groupedSchemes, "groupedSchemesgroupedSchemes");
  // };
  /**
   * 处理筛选条件变化
   */
  const handleFilterChange = (key, value) => {
    console.log(key, "key, valuekey, value");
    console.log(value, "valuevalue");

    // 核心：更新筛选状态，触发后续筛选逻辑
    setFilters((prev) => ({
      ...prev,
      [key]: value,
    }));

    // 优化体验：选择项目后自动展开该项目
    if (key === "projectId" && value !== "all") {
      setExpandedProjects((prev) => ({
        ...prev,
        [value]: true,
      }));
    }
  };
  /**
   * 手动刷新数据
   */
  const handleRefresh = () => {
    console.log("🔄 手动刷新数据...");
    loadAllData(true, true);
  };

  /**
   * 跳转到方案分析页面
   */
  const handleViewAnalysis = (schemeId) => {
    if (!schemeId) {
      toast({
        variant: "destructive",
        title: "跳转失败",
        description: "方案ID为空，无法跳转",
      });
      return;
    }

    const validSchemeId = String(schemeId).trim();
    const targetScheme = ensureArray(schemes).find(
      (s) => s.id === validSchemeId
    );

    // 构建目标URL（编码特殊字符）
    const baseUrl = createPageUrl("SchemeAnalysis");
    const targetUrl = `${baseUrl}?schemeId=${encodeURIComponent(
      validSchemeId
    )}`;

    try {
      navigate(targetUrl, {
        state: {
          schemeId: validSchemeId,
          schemeName: targetScheme?.name || "未知方案",
          fromPage: "ConstructionSchemes",
          timestamp: Date.now(),
        },
      });
    } catch (error) {
      console.error("❌ 跳转方案分析页失败:", error);
      toast({
        variant: "destructive",
        title: "跳转失败",
        description: `页面跳转失败: ${error.message}`,
      });
    }
  };

  /**
   * 打开新建方案表单
   */
  const handleCreateNewScheme = () => {
    setEditingScheme(null);
    setIsFormVisible(true);
  };

  /**
   * 打开编辑方案表单
   */
  const handleEditScheme = (scheme) => {
    setEditingScheme(scheme);
    setIsFormVisible(true);
  };

  /**
   * 删除方案
   */
  const handleDeleteScheme = async (schemeId) => {
    const schemeToDelete = schemes.find((s) => s.id === schemeId);
    if (!schemeToDelete) return;

    // 确认删除
    if (
      !window.confirm(
        `确定要删除施工方案"${schemeToDelete.name}"吗？删除后不可恢复！`
      )
    ) {
      return;
    }

    try {
      await apiCallWithRetry(() => ConstructionSchemeAPI.delete(schemeId));
      toast({
        title: "删除成功",
        description: `施工方案"${schemeToDelete.name}"已删除`,
      });
      loadAllData(true); // 重新加载数据
    } catch (error) {
      console.error("❌ 删除方案失败:", error);
      toast({
        variant: "destructive",
        title: "删除失败",
        description: error.message || "删除方案时发生错误，请稍后重试",
      });
    }
  };

  /**
   * 提交方案（新建/编辑）
   */
  const handleSchemeSubmit = async (formData) => {
    try {
      if (editingScheme) {
        // 编辑模式：传递方案ID和更新数据
        let res = await apiCallWithRetry(() =>
          ConstructionSchemeAPI.update(editingScheme.id, formData)
        );
        if (res.code == 500) {
          toast({
            title: "更新失败",
            description: res.msg,
          });
        } else {
          toast({
            title: "更新成功",
            description: `施工方案"${formData.name}"已更新`,
          });
        }
      } else {
        // 新建模式：传递完整表单数据
        let res = await apiCallWithRetry(() =>
          ConstructionSchemeAPI.create(formData)
        );

        if (res.code == 500) {
          toast({
            title: "创建失败",
            description: res.msg,
          });
        } else {
          toast({
            title: "创建成功",
            description: `施工方案"${formData.name}"已创建`,
          });
        }
      }

      // 关闭表单并刷新数据
      setIsFormVisible(false);
      setEditingScheme(null);
      loadAllData(true);
    } catch (error) {
      console.error("❌ 保存方案失败:", error);
      toast({
        variant: "destructive",
        title: "保存失败",
        description: error.message || "保存方案时发生错误，请检查数据后重试",
      });
    }
  };

  /**
   * 渲染状态徽章
   */
  const getStatusBadge = (statusKey) => {
    const status = statusMap[statusKey] || statusMap.draft;
    return (
      <Badge
        className={`${status.color} flex items-center gap-1 w-fit px-2 py-1`}
      >
        {status.icon}
        <span className="text-xs">{status.label}</span>
      </Badge>
    );
  };

  /**
   * 获取所有唯一的施工方法（用于筛选）
   */
  const uniqueMethods = useMemo(() => {
    const methods = new Set(
      ensureArray(schemes)
        .map((s) => s.constructionMethod)
        .filter(Boolean)
    );
    return Array.from(methods).sort();
  }, [schemes]);

  const groupedSchemes = useMemo(() => {
    const groups = {};
    // 按项目ID分组（确保分组关联正确projectId）
    filteredSchemes.forEach((scheme) => {
      const projectId = scheme.projectId || "unknown";
      if (!groups[projectId]) {
        const project = projects.find((p) => p.id === projectId) || {
          id: "unknown",
          name: "未知项目",
          description: "未关联到任何有效项目",
        };

        groups[projectId] = {
          projectId: projectId, // 明确存储projectId，方便后续扩展
          project,
          schemes: [],
        };
      }
      groups[projectId].schemes.push(scheme);
    });

    // 按项目名称正序排序（修复属性名错误）
    return Object.values(groups).sort((a, b) => {
      return a.project.projectName.localeCompare(b.project.projectName);
    });
  }, [filteredSchemes, projects]);

  return (
    <div className="p-4 md:p-6 space-y-6 bg-gray-50 min-h-screen">
      <div className="max-w-screen-2xl mx-auto">
        <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6 mb-8">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2">
              施工方案管理
            </h1>
            <p className="text-gray-600">查看、筛选和管理跨越点施工方案</p>
          </div>
          <div className="flex items-center gap-3 mt-4 md:mt-0 flex-wrap">
            <Button
              variant="outline"
              onClick={handleRefresh}
              disabled={isLoading}
              className="flex items-center gap-2"
            >
              {isLoading ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <RefreshCw className="w-4 h-4" />
              )}
              刷新
            </Button>

            <Button onClick={handleCreateNewScheme} disabled={isLoading}>
              <Plus className="mr-2 h-4 w-4" /> 新建方案
            </Button>
          </div>
        </div>

        {/* 错误提示区域 */}
        {error && (
          <Alert variant="destructive" className="mb-6">
            <AlertTriangle className="h-4 w-4" />
            <AlertDescription className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2">
              <div>
                <p className="font-medium">数据加载遇到问题</p>
                <p className="text-sm">{error}</p>
                {lastSuccessfulLoad && (
                  <p className="text-xs text-gray-500 mt-1">
                    上次成功加载: {lastSuccessfulLoad.toLocaleString()}
                  </p>
                )}
              </div>
              <Button
                variant="outline"
                size="sm"
                onClick={handleRefresh}
                className="ml-0 sm:ml-4 mt-2 sm:mt-0"
              >
                <RefreshCw className="w-4 h-4 mr-1" />
                重试
              </Button>
            </AlertDescription>
          </Alert>
        )}

        {/* 筛选区域 */}
        <Card className="mb-6 border-gray-200">
          <CardContent className="p-4 space-y-3">
            {/* 筛选提示（数据量较大时） */}
            {filters.projectId === "all" && filteredSchemes.length > 20 && (
              <Alert className="bg-blue-50 border-blue-200">
                <Info className="h-4 w-4 text-blue-600" />
                <AlertDescription className="text-blue-800 text-sm">
                  <span className="font-medium">提示：</span>
                  当前显示所有项目的施工方案（共{filteredSchemes.length}
                  个），建议选择具体项目缩小范围。
                </AlertDescription>
              </Alert>
            )}

            <div className="flex flex-col lg:flex-row gap-4">
              {/* 搜索框 */}
              <div className="relative flex-1">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                <Input
                  placeholder="搜索方案名称、施工方法或勘查单..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10 h-10"
                />
              </div>

              {/* 筛选器组件 */}
              <SchemeFilters
                filters={filters}
                onFilterChange={handleFilterChange}
                projects={projects}
                methodTemplates={methodTemplates}
                uniqueMethods={uniqueMethods}
                statusMap={statusMap}
              />
            </div>
          </CardContent>
        </Card>

        {/* 方案表单（新建/编辑） */}
        {isFormVisible && (
          <SchemeForm
            isOpen={isFormVisible}
            onCancel={() => {
              setIsFormVisible(false);
              setEditingScheme(null);
            }}
            onSubmit={handleSchemeSubmit}
            scheme={editingScheme}
            projects={ensureArray(projects)}
            tensionSections={ensureArray(tensionSections)}
            crossingPoints={ensureArray(crossingPoints)}
            tensionSection={ensureArray(tensionSections)}
            methodTemplates={ensureArray(methodTemplates)}
            availableStandards={standards}
          />
        )}

        {/* 方案列表区域 */}
        <div className="space-y-6 mt-6">
          {/* 加载中骨架屏 */}
          {isLoading ? (
            Array.from({ length: 3 }).map((_, projectIndex) => (
              <Card
                key={`skeleton-project-${projectIndex}`}
                className="animate-pulse border-gray-200"
              >
                <CardHeader className="flex flex-row items-center justify-between p-4">
                  <div className="h-6 bg-gray-200 rounded w-1/3"></div>
                  <div className="h-4 bg-gray-200 rounded w-1/12"></div>
                </CardHeader>
                <CardContent className="border-t pt-4 space-y-4">
                  {Array.from({ length: 2 }).map((_, schemeIndex) => (
                    <div
                      key={`skeleton-scheme-${projectIndex}-${schemeIndex}`}
                      className="flex items-center space-x-4 p-4 border rounded-md bg-gray-50"
                    >
                      <div className="h-10 w-10 bg-gray-200 rounded-full"></div>
                      <div className="flex-1 space-y-2">
                        <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                        <div className="h-3 bg-gray-100 rounded w-1/2"></div>
                      </div>
                      <div className="h-8 w-16 bg-gray-200 rounded"></div>
                    </div>
                  ))}
                </CardContent>
              </Card>
            ))
          ) : error && !schemes.length ? (
            <Card className="border-gray-200">
              <CardContent className="p-8 text-center">
                <AlertTriangle className="w-16 h-16 text-red-300 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-gray-900 mb-2">
                  无法加载施工方案数据
                </h3>
                <p className="text-gray-600 mb-6">{error}</p>
                <Button onClick={handleRefresh}>
                  <RefreshCw className="w-4 h-4 mr-2" />
                  重新加载
                </Button>
              </CardContent>
            </Card>
          ) : filteredSchemes.length === 0 ? (
            <div className="text-center py-10 text-gray-500 bg-white rounded-lg border border-gray-200 p-6">
              <FileText className="mx-auto h-12 w-12 text-gray-400" />
              <h3 className="mt-2 text-sm font-medium text-gray-900">
                没有找到匹配的施工方案
              </h3>
              <p className="mt-1 text-sm text-gray-500 max-w-md mx-auto">
                {tensionSections.length === 0
                  ? "请先在「勘察单管理」中创建勘查单，再创建施工方案。"
                  : "请尝试调整筛选条件（如项目、状态）或创建新方案。"}
              </p>
              {tensionSections.length > 0 && (
                <Button onClick={handleCreateNewScheme} className="mt-4">
                  <Plus className="w-4 h-4 mr-2" />
                  创建新方案
                </Button>
              )}
            </div>
          ) : (
            groupedSchemes.map(({ project, schemes: projectSchemes }) => (
              <Card key={project.id} className="border-gray-200">
                {/* 项目头部（可展开/折叠） */}
                <CardHeader
                  className="flex flex-row items-center justify-between p-4 cursor-pointer hover:bg-gray-50"
                  onClick={() => toggleProjectExpansion(project.id)}
                >
                  <div className="flex items-center space-x-2">
                    {expandedProjects[project.id] ? (
                      <ChevronDown className="h-5 w-5 text-gray-600" />
                    ) : (
                      <ChevronRight className="h-5 w-5 text-gray-600" />
                    )}
                    <CardTitle className="text-lg">
                      {project.projectName}
                    </CardTitle>
                    <Badge variant="secondary" className="h-6 px-2">
                      {projectSchemes.length} 个方案
                    </Badge>
                  </div>
                </CardHeader>

                {/* 项目下的方案列表（展开时显示） */}
                {expandedProjects[project.id] && (
                  <CardContent className="border-t pt-4 space-y-4">
                    {projectSchemes.map((scheme) => (
                      <div
                        key={scheme.id}
                        className="flex flex-col sm:flex-row items-start sm:items-center justify-between p-4 border rounded-lg hover:bg-gray-50 transition-colors"
                      >
                        {/* 方案基本信息 */}
                        <div className="flex-1 mb-3 sm:mb-0">
                          <div className="flex items-center gap-3">
                            <FileText className="w-5 h-5 text-blue-600 flex-shrink-0" />
                            <div>
                              <h4
                                className="font-medium text-sm cursor-pointer"
                                onClick={() => handleViewAnalysis(scheme.id)}
                              >
                                {scheme.name}
                              </h4>
                              <p className="text-xs text-gray-500 mt-1">
                                勘查单: {scheme.tensionSectionName}
                              </p>
                            </div>
                          </div>
                        </div>

                        {/* 方案状态与操作 */}
                        <div className="flex items-center gap-3">
                          {/* 状态徽章 */}
                          {getStatusBadge(scheme.approvalStatus)}

                          {/* 操作下拉菜单 */}
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button
                                variant="ghost"
                                size="icon"
                                className="h-8 w-8"
                              >
                                <MoreVertical className="w-4 h-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end" className="w-48">
                              <DropdownMenuItem
                                onClick={() => handleViewAnalysis(scheme.id)}
                                className="text-sm"
                              >
                                <Eye className="w-4 h-4 mr-2" />
                                查看分析
                              </DropdownMenuItem>
                              <DropdownMenuItem
                                onClick={() => handleEditScheme(scheme)}
                                className="text-sm"
                              >
                                <Edit className="w-4 h-4 mr-2" />
                                编辑
                              </DropdownMenuItem>
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                onClick={() => handleDeleteScheme(scheme.id)}
                                className="text-sm text-red-600"
                              >
                                <Trash2 className="w-4 h-4 mr-2" />
                                删除
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </div>
                      </div>
                    ))}
                  </CardContent>
                )}
              </Card>
            ))
          )}
        </div>
      </div>
    </div>
  );
}
